<script setup lang="ts">
import {getAssignTreeApi} from '@/api/menu/index.ts'
import {saveAssignApi} from '@/api/role/index.ts'
import {reactive, ref} from "vue";
import useDialog from "@/hooks/useDialog.ts";
import SysDialog from "@/components/dialog/SysDialog.vue";
import {ElMessage, ElTree} from "element-plus";
import {AssignMenuParam, SysRole} from "@/api/role/type.ts";
// 弹框属性
const {dialog, onShow, onClose, onConfirm} = useDialog()

// 树的属性配置
const defaultProps = {
  children: 'children',
  label: 'title',
}
const treeRef = ref<InstanceType<typeof  ElTree>>()

// 树数据
const assignTreeData = reactive({
  list: [],
  assignTreeChecked: []
})

const formData = reactive({
  roleId: undefined,
  roleName: '',
  code:'',
})

/**
 *
 * @param id 拥有的菜单id
 * @param data 全部菜单数组
 * @param newArr 处理后选中的菜单数组
 */
const checked = (id: number, data: any, newArr: any) => {
  data.forEach((item: any) => {
    console.log(item.id )
    console.log(id)
    if (item.id == id) {
      console.log(item.id)
      if (item.children && item.children.length == 0) {
        console.log(item.id)
        newArr.push(item.id)
      }
    } else {
      console.log(11111)
      if (item.children && item.children.length != 0) {
        //递归调用
        checked(id, item.children, newArr)
      }
    }
  })
}
// 查询菜单树
const getAssignTree = async (roleId: number) => {
  try {
    let res = await getAssignTreeApi(roleId)
    assignTreeData.list = res.data.listMenu
    assignTreeData.assignTreeChecked = res.data.checkList
    console.log( )
    // 数据回显，判断角色原来是否已经有分配过权限，如果有则勾选
    if (assignTreeData.assignTreeChecked.length > 0) {
      let newArr: any = [];
      assignTreeData.assignTreeChecked.forEach((item) => {
        console.log(item)
        checked(item, assignTreeData.list, newArr)
      })
      assignTreeData.assignTreeChecked = newArr
    }
    console.log('树形数据:', assignTreeData.list)
    console.log('选中节点:', assignTreeData.assignTreeChecked)
  } catch (error) {
    console.log(error)
  }
}

// 弹框显示
const show = async (row: SysRole) => {
  console.log()
  //设置弹框熟悉
  dialog.width = 600
  dialog.height = 400
  dialog.title = '分配菜单'
  assignTreeData.assignTreeChecked = []
  assignTreeData.list = []


  // 表单仅仅显示
  formData.roleName = row.roleName
  formData.code = row.code

  commitParam.roleId = row.id;
  commitParam.permissionIdList = []
  // 获取树数据
  await getAssignTree(row.id as number)
  onShow()
}

// 提交数据
const commitParam = reactive(<AssignMenuParam>{
  roleId: undefined,
  permissionIdList: [],
})
// 提交表单
const commit = async () => {
  try {
    console.log(treeRef.value?.getCheckedKeys());
    console.log(treeRef.value?.getHalfCheckedKeys());
    const checkIds = treeRef.value?.getCheckedKeys() as number[]
    const halfCheckIds = treeRef.value?.getHalfCheckedKeys() as number[]
    if (checkIds.length == 0) {
      ElMessage.warning('请选择要分配的菜单')
      return
    }
    console.log("分配结果"+checkIds?.concat(halfCheckIds))
    commitParam.permissionIdList = checkIds?.concat(halfCheckIds)
    await saveAssignApi(commitParam)
    ElMessage.success('分配成功')
    onClose()
  } catch (error) {
    console.log()
  }
}
// 暴露给外部组件使用
defineExpose({
  show
})


</script>

<template>
  <SysDialog
      :title="dialog.title"
      :width="dialog.width"
      :height="dialog.height"
      :visible="dialog.visible"
      @on-close="onClose"
      @on-confirm="commit">

    <template v-slot:content>
      <el-form :model="formData" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="formData.roleName" disabled />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="formData.code" disabled />
        </el-form-item>


        <!-- 自定义数据权限时显示部门树 -->
        <el-form-item label="菜单权限">
          <el-tree  ref="treeRef"
                    style="width: 100%"
                    default-expand-all
                    :data="assignTreeData.list"
                    :props="defaultProps"
                    :default-checked-keys="assignTreeData.assignTreeChecked"
                    node-key="id" show-checkbox
                    class="permission-tree">
          </el-tree>
        </el-form-item>
      </el-form>
    </template>
  </SysDialog>
</template>

<style scoped lang="scss">
.permission-tree {
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-select) {
  width: 100%;
}
</style>
